package leetcode;

public class ReverseKGroup {

    static class ListNode{
        int  val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k){
        if(head == null || head.next == null || k == 1){
            return head;
        }
        ListNode node = new ListNode(0);
        node.next  = head;
        ListNode newHead = null;
        while (true){
            if(node == null){
                break;
            }
            ListNode preHead = node;
            ListNode[] nodes = new ListNode[k];
            nodes[0] = node.next;
            for(int i = 1; i < k; i++){
                if(nodes[i - 1] != null){
                    if(nodes[i - 1].next == null){
                        return newHead == null?head: newHead;
                    }
                    nodes[i] = nodes[i - 1].next;
                }else{
                    return newHead == null?head: newHead;
                }
            }
            ListNode temp = nodes[k - 1].next;
            for(int i = 0; i < k; i++){
                if( i == 0){
                    preHead.next = nodes[k - i - 1];
                }/*else if(k - i - 1 == 0){
                    nodes[k - i - 1].next = nodes[0].next;
                }*/
                int index = k - i - 2;
                if(index >= 0){
                    nodes[k - (i + 1)].next = nodes[index];
                }else{
                    nodes[k - (i + 1)].next = temp;
                }
            }
            if(newHead == null){
                newHead = nodes[k - 1];
            }
            node = nodes[0];
        }
        return newHead == null? head: newHead;
    }

    public static void main(String[] args) {
        int[] arr= {1, 2, 3, 4, 5};
        ListNode head = new ListNode(0);
        ListNode node = head;
        for(int i = 0; i < arr.length; i++){
            node.next = new ListNode(arr[i]);
            node = node.next;
        }
        ReverseKGroup group = new ReverseKGroup();
        group.reverseKGroup(head.next, 2);
    }

}
